package com.android.support.lib.universal.views;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.android.support.lib.universal.R;
import com.android.support.lib.universal.base.BaseApplication;
import com.android.support.lib.universal.utils.UtilAssets;
import com.android.support.lib.universal.utils.UtilProportion;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by Administrator on 2017/5/14.
 */
public class MainUpView extends View {
    public MainUpView(Context context) {
        super(context);
        init();
    }

    public MainUpView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
//        这个尽量不要使用硬件加速。效果会有问题。
//        Paint paint=new Paint();
//        paint.setAntiAlias(true);
//        paint.setDither(true);
//        setLayerType(LAYER_TYPE_HARDWARE, paint);

        setFocusable(false);
        setBackground(UtilAssets.getInstance(BaseApplication.getInstance()).getNinePatchDrawable(R.drawable.mainupview_white_light_10));//设置九文件
        padding = (int) (padding * UtilProportion.getInstance((Activity) getContext()).getHorizontalProportion());
        timer = new Timer();
        timer.schedule(new AlphaTimerTask(), 10, 200);//呼吸灯效果
    }

    private float scale = 1.08f;
    private int padding = 10;
    private View newView, oldView;
    private Map<String, Long> mappriority = new HashMap<>();

    public void setFocuseView(View newView, View oldView) {
        if (oldView != null && this.newView != null && (oldView != this.newView)) {
            //Log.e("test", "等于：\t" + (oldView == this.newView));
            final View view = this.newView;
            this.newView.post(new Runnable() {
                @Override
                public void run() {
                    //异常修复
                    view.setScaleX(1);
                    view.setScaleY(1);
                    //Log.e("test","异常修复");
                }
            });
        }
        if (oldView != null && this.newView == null) {
            //Log.e("test","异常修复2");
            oldView = null;
        }
        if (newView != null && this.newView == newView) {
            //防止重复聚焦
            //Log.e("test","重复聚焦:\t"+newView.getScaleX());
            final View view = this.newView;
            this.newView.post(new Runnable() {
                @Override
                public void run() {
                    //异常修复
                    view.setScaleX(scale);
                    view.setScaleY(scale);
                    setVisibility(VISIBLE);
                    //Log.e("test","异常修复");
                }
            });
            return;
        }
        if (newView == null && oldView != null) {
            if (oldView.getScaleX() == 1) {
                if (getVisibility() != INVISIBLE) {
                    setVisibility(INVISIBLE);//如果聚焦控件为null,则不会显示出来。
                }
                return;//没有缩放的必要
            }
        }
        this.newView = newView;
        this.oldView = oldView;
        if (newView != null) {
            timer.schedule(new ScaleTimerTask(newView, oldView, System.currentTimeMillis()), 10, 50);//参数二开始启动时间不要为0，延迟一点，效果好。
            if (newView.getParent() != null) {
                if (newView.getParent().getParent() != null) {
                    ((View) (newView.getParent().getParent())).bringToFront();
                }
                ((View) (newView.getParent())).bringToFront();
            }
            newView.bringToFront();
            bringToFront();
            requestLayout();
        } else {
            timer.schedule(new ScaleTimerTask(newView, oldView, System.currentTimeMillis()), 10, 50);//参数二开始启动时间不要为0，延迟一点，效果好。
        }
        setVisibility(INVISIBLE);//不要使用GONE,避免获取参数失败
    }

    private Timer timer;
    private float alpha = 0;
    private boolean isAdd = true;

    //呼吸灯效果
    class AlphaTimerTask extends TimerTask {

        @Override
        public void run() {
            post(new Runnable() {
                @Override
                public void run() {
                    if (isAdd) {
                        alpha = alpha + 0.1f;
                    } else {
                        alpha = alpha - 0.1f;
                    }
                    if (alpha > 1) {
                        alpha = 1;
                        isAdd = false;
                    } else if (alpha < 0.4) {
                        alpha = 0.4f;
                        isAdd = true;
                    }
                    setAlpha(alpha);
                }
            });
        }
    }

    long Delay = 0;

    //缩放效果
    class ScaleTimerTask extends TimerTask {
        private View mNewView;
        private View mOldView;
        private float maxScale = 1f;
        private float minScale = scale;
        private long priority;
        private boolean bNewView = true,//是否可操作(异常，或为null，则不可操作)
                bOldView = true, isExe = false;

        public ScaleTimerTask(View mNewView, View mOldView, long priority) {
            this.mNewView = mNewView;
            this.mOldView = mOldView;
            this.priority = priority;
            if (mOldView != null) {
                mappriority.put("" + mOldView.getId(), priority);
            }
            if (mNewView != null) {
                mappriority.put("" + mNewView.getId(), priority);
            }
            if ((System.currentTimeMillis() - Delay) < 50) {
                //Log.e("test","delay:\t"+(System.currentTimeMillis() - Delay));
                isExe = true;//焦点移动太快，作为异常处理,速度太快不放人UI主线程，会堵塞
            }
            Delay = System.currentTimeMillis();
            //Log.e("test","开始:\tmaxScale:\t"+maxScale+"\tminScale:\t"+minScale);
        }

        @Override
        public void run() {
            //逻辑运算
            if (minScale > 1) {
                minScale = minScale - 0.025f;
            }
            if (maxScale < scale) {
                maxScale = maxScale + 0.025f;
            }
            //结束
            if (maxScale >= scale || minScale <= 1 || (!bNewView && !bOldView) || isExe) {
                //Log.e("test","结束==================================================================maxScale:\t"+maxScale+"\tminScale:\t"+minScale+"\tb:\t"+(!bNewView && !bOldView)+"\tisExe:\t"+isExe);
                maxScale = scale;
                minScale = 1f;
                cancel();
                System.gc();
            }
            //失焦控件
            if (mOldView != null && mOldView != mNewView && mOldView != newView && bOldView) {
                if (mappriority.containsKey("" + mOldView.getId())) {
                    bOldView = priority >= mappriority.get("" + mOldView.getId());
                }
            } else {
                bOldView = false;
            }
            //聚焦控件
            if (mNewView != null && mNewView != oldView && bNewView) {
                if (mappriority.containsKey("" + mNewView.getId())) {
                    bNewView = priority >= mappriority.get("" + mNewView.getId());
                }
            } else {
                bNewView = false;
            }
            //防止线程错乱(效果明显),防止聚焦时和失去焦点时不是同一个对象。
            if (mOldView != null && mOldView.getScaleX() < minScale) {
                //Log.e("test","子线程终止:\t"+mOldView.getScaleX()+"\tminScale:\t"+minScale);
                return;
            }
            if (mNewView != null && mNewView.getScaleX() > maxScale) {
                //Log.e("test","子线程终止:\t"+mNewView.getScaleX()+"\tmaxScale:\t"+maxScale);
                return;
            }
            //Log.e("test","bNewView:\t"+bNewView+"\tbOldView:\t"+bOldView+"\tisExe:\t"+isExe);
            //UI更新
            if ((bNewView || bOldView) && !isExe) {
                post(new Runnable() {
                    @Override
                    public void run() {
                        if (bOldView) {
                            //Log.e("test","变小:\t"+minScale);
                            mOldView.setScaleX(minScale);
                            mOldView.setScaleY(minScale);
                            if (minScale == 1) {
                                bOldView = false;
                            }
                        }
                        if (bNewView) {
                            //Log.e("test", "变大:\t" + maxScale + "\tid:\t" + mNewView.getId());
                            cMaxScale = maxScale;
                            mNewView.setScaleX(maxScale);
                            mNewView.setScaleY(maxScale);
                            setScaleX(maxScale);
                            setScaleY(maxScale);
                            if (maxScale == scale) {
                                bNewView = false;
                            }
                            if (getVisibility() != VISIBLE) {
                                setVisibility(VISIBLE);//如果聚焦控件为null,则不会显示出来。
                            }
                        }
                    }
                });
            }
        }
    }

    float cMaxScale = 1;

    @Override
    public void layout(int l, int t, int r, int b) {
        if (newView == null) {
            super.layout(l, t, r, b);
        } else {
            Rect rect = new Rect();
            newView.setScaleX(1);
            newView.setScaleY(1);
            newView.getGlobalVisibleRect(rect);
            super.layout(rect.left - padding, rect.top - padding, rect.right + padding, rect.bottom + padding);
        }

    }
}
